package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.*;
import cn.wolfcode.wolf2w.query.StrategyCommentQuery;

import cn.wolfcode.wolf2w.repostiory.StrategyCommentRepository;
import cn.wolfcode.wolf2w.service.*;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;


@Service
//@Transactional  暂时先别管事务
public class StrategyCommentServiceImpl implements IStrategyCommentService {


    @Autowired
    private StrategyCommentRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public StrategyComment get(String id) {
        StrategyComment strategyComment = repository.findById(id).orElse(null);

        return strategyComment;
    }

    @Override
    public Page<StrategyComment> query(StrategyCommentQuery qo) {
        Query query = new Query();
        if (StringUtils.hasLength(qo.getStrategyId())) {
            query.addCriteria(Criteria.where("strategyId").is(qo.getStrategyId()));
        }

        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, "createTime");


        return DBHelper.query(template, StrategyComment.class, query, pageable);
    }

    @Override
    public List<StrategyComment> list() {
        List<StrategyComment> list = repository.findAll();
        return list;
    }

    @Override
    public void upDate(StrategyComment strategyComment) {
        repository.save(strategyComment);
    }

    @Override
    public void save(StrategyComment strategyComment) {
        strategyComment.setId(null);
        strategyComment.setCreateTime(new Date());
        repository.save(strategyComment);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public void commentThumb(String cid, String id) {
        //得到当前评论
        StrategyComment strategyComment = this.get(cid);
        //获取点赞id集合
        List<String> thumbuplist = strategyComment.getThumbuplist();
        //点赞集合中没有当前点赞用户的id
        if (!thumbuplist.contains(id)){
            strategyComment.setThumbupnum(strategyComment.getThumbupnum()+1);
            thumbuplist.add(id);
        }else {
            strategyComment.setThumbupnum(strategyComment.getThumbupnum()-1);
            thumbuplist.remove(id);
        }
        //更新数据库
        this.upDate(strategyComment);
    }


}
